import Cookies from 'js-cookie';
import { ChainType } from '@/config/chains';

const TOKEN_KEY_PREFIX = 'admin_token';
const REFRESH_KEY_PREFIX = 'admin_refresh_token';

// Helper functions to generate chain-specific keys
const getTokenKey = (chain: ChainType): string => `${TOKEN_KEY_PREFIX}_${chain}`;
const getRefreshKey = (chain: ChainType): string => `${REFRESH_KEY_PREFIX}_${chain}`;

export const getAuthToken = (chain: ChainType): string | undefined => {
  return Cookies.get(getTokenKey(chain));
};

export const setAuthToken = (token: string, chain: ChainType): void => {
  Cookies.set(getTokenKey(chain), token, { expires: 7 }); // 7 days
};

export const removeAuthToken = (chain: ChainType): void => {
  Cookies.remove(getTokenKey(chain));
  Cookies.remove(getRefreshKey(chain));
};

export const removeAllAuthTokens = (): void => {
  const chains: ChainType[] = ['mainnet', 'testnet'];
  chains.forEach(chain => {
    Cookies.remove(getTokenKey(chain));
    Cookies.remove(getRefreshKey(chain));
  });
};

export const getRefreshToken = (chain: ChainType): string | undefined => {
  return Cookies.get(getRefreshKey(chain));
};

export const setRefreshToken = (token: string, chain: ChainType): void => {
  Cookies.set(getRefreshKey(chain), token, { expires: 30 }); // 30 days
};

export const isAuthenticated = (chain: ChainType): boolean => {
  return !!getAuthToken(chain);
};

// Get authentication status for all chains
export const getAuthStatus = (): Record<ChainType, boolean> => {
  return {
    mainnet: isAuthenticated('mainnet'),
    testnet: isAuthenticated('testnet'),
  };
};